package com.lujianfei.componentdesign.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.lujianfei.componentdesign.R

class CustomTabHost @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    companion object {
        const val TAG = "CustomTabHost"
    }

    var container: LinearLayout ?= null
    var onTabClickListener: ((CustomTab)->Unit) ?= null

    init {
        LayoutInflater.from(context).inflate(R.layout.widget_custom_tabhost, this, true)
        container = findViewById(R.id.container)
    }

    fun addTab(customTab:CustomTab) {
        val layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1f)
        customTab.layoutParams = layoutParams
        container?.addView(customTab)
        customTab.setOnClickListener {
            reset()
            customTab.setTabSelected(true)
            onTabClickListener?.invoke(customTab)
        }
    }

    private fun reset() {
        container?.childCount?.let {childCount->
            for( idx in 0 until childCount ) {
                val childAt = container?.getChildAt(idx)
                if (childAt is CustomTab) {
                    childAt.setTabSelected(false)
                }
            }
        }
    }
}